<template>
  <el-upload
      class="avatar-uploader"
      action="#"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
      :http-request="handleUpload"
  >
    <img v-if="previewUrl" :src="previewUrl" class="avatar"/>
    <el-icon v-else class="avatar-uploader-icon">
      <Plus/>
    </el-icon>
  </el-upload>
</template>

<script lang="ts" setup>
import {ref, watch} from 'vue'
import {ElMessage} from 'element-plus'
import {Plus} from '@element-plus/icons-vue'
import type {UploadProps} from 'element-plus'
import {uploadFile} from '@/api/request'

const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  }
})

const emit = defineEmits(['update:modelValue'])

// 用于预览的URL
const previewUrl = ref('')

// 监听modelValue变化，更新预览图
watch(() => props.modelValue, (newValue) => {
  previewUrl.value = newValue
}, {immediate: true})

// 处理文件上传
const handleUpload = async (options) => {
  console.log('Upload options:', options)
  try {
    // 使用原始File对象
    const file = options.file;
    console.log('File to upload:', file);
    
    const response = await uploadFile(
        '/api/system/ufr/upload/facePic',
        file,
        'facePic', // 修改字段名为facePic，根据后端API要求
        {}, // 无额外数据
        {
          // 明确移除Content-Type，让浏览器自动添加
          headers: {}
        }
    )
    console.log('Upload response:', response);

    // 手动调用成功回调
    handleAvatarSuccess(response, options.file)

    // 通知el-upload组件上传成功
    options.onSuccess(response)
  } catch (error) {
    console.error('Upload error:', error);
    // 处理错误
    ElMessage.error('头像上传失败: ' + (error.message || '未知错误'))
    options.onError(error)
  }
}

const handleAvatarSuccess = (
    response,
    file
) => {
  if (response && response.code === 200) {
    // 假设后端返回的数据格式为 {code: 200, data: {url: 'image_url'}} 或 {code: 200, data: 'image_url'}
    const imageUrl = response.data.url || response.data
    previewUrl.value = imageUrl
    emit('update:modelValue', imageUrl)
    ElMessage.success('头像上传成功')
  } else {
    ElMessage.error('头像上传失败: ' + (response.msg || '未知错误'))
  }
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  // 允许多种图片格式
  const isImage = ['image/jpeg', 'image/png', 'image/gif'].includes(rawFile.type)
  const isLt2M = rawFile.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('头像必须是JPG/PNG/GIF格式!')
    return false
  } else if (!isLt2M) {
    ElMessage.error('头像大小不能超过2MB!')
    return false
  }
  return true
}
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
